package conn;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class Conn {
    private static Connection connection = null;

    //读取配置文件
    public  String getValue(String key)
    {
        String configFile = "system.properties";    //指定根目录
        Properties ini = new Properties();
        InputStream is = getClass().getResourceAsStream(configFile);//把资源文件读入到流
        try
        {
            ini.load(is);
            is.close();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return ini.getProperty(key);
    }

    // 使用静态方法获取连接数据库
    public  Connection open()
    {
        // 拿到具体的数据库连接的属性值
        String driver = getValue("jdbc.driver");
        String url = getValue("jdbc.connection.url");
        String user = getValue("jdbc.connection.user");
        String password = getValue("jdbc.connection.password");
        try
        {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, user, password);
        }
        catch (Exception e)
        {
            throw new RuntimeException("数据库连接异常！");
        }
        return connection;
    }

    // 关闭数据库
    public  void close(Connection conn)
    {
        if (conn != null)
        {
            try
            {
                conn.close();
            } catch (SQLException e)
            {
                throw new RuntimeException("数据库关闭异常！");
            }
        }
    }

}
